package docker_adapter

import (
	"context"
	"fmt"
	"strings"

	"octopus/internal/domain/entities"
	"octopus/internal/domain/interfaces"

	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
)

type dockerContainerRepository struct {
	cli *client.Client
}

func NewDockerContainerRepository() interfaces.ContainerRepository {
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		panic(err)
	}
	return &dockerContainerRepository{cli: cli}
}

func (r *dockerContainerRepository) List() ([]*entities.Container, error) {
	containers, err := r.cli.ContainerList(context.Background(), container.ListOptions{})
	if err != nil {
		return nil, err
	}

	var result []*entities.Container
	for _, c := range containers {
		ports := make([]string, len(c.Ports))
		for i, p := range c.Ports {
			ports[i] = fmt.Sprintf("%d->%d/%s", p.PublicPort, p.PrivatePort, p.Type)
		}
		result = append(result, &entities.Container{
			ID:     c.ID[:12],
			Name:   strings.TrimPrefix(c.Names[0], "/"),
			Image:  c.Image,
			Status: c.Status,
			Ports:  ports,
		})
	}

	return result, nil
}

func (r *dockerContainerRepository) Stop(id string) error {
	return r.cli.ContainerStop(context.Background(), id, container.StopOptions{})
}

// Restart restarts a container by its ID.
func (r *dockerContainerRepository) Restart(id string) error {
	return r.cli.ContainerRestart(context.Background(), id, container.StopOptions{})
}